local skynet = require "skynet"
local Services = require "global.Services"

-- service -> {watcher, watcher2, ...}
local watchers = {}
local CMD = {}

skynet.register_protocol {
    name = "client",
    id = skynet.PTYPE_CLIENT, -- PTYPE_CLIENT = 3
    unpack = function() end,
    dispatch = function(_, address)
        -- address 退出
        Services.HOT_MGR:remove(address)
        if watchers[address] then
            for _, watcher in ipairs(watchers[address]) do
                skynet.send(watcher, "lua", "on_service_exit", address)
            end
        end
    end
}

function CMD.monitor(address, watcher)
    if not watchers[address] then
        watchers[address] = {}
    end

    table.insert(watchers[address], watcher)
end

skynet.start(function()
    skynet.dispatch_lua(CMD)
end)
